<!--分页table-->
<template>
  <div>
    <!-- :header-cell-style="handleTheadStyle" -->
    <el-table
      v-loading="loading"
      :data="list"
      :height="height"
      ref="mutipleTable"
      :border="border"
      fit
      :default-sort="defaultSort"
      :header-cell-style="{ 'background': 'rgb(246, 248, 252)' }"
      :scrollbar-always-on="showScroll"
      @select-all="handleSelectionChangeAll"
      @selection-change="handleSelectionChange"
      @current-change="handleCurrentChange"
      @sort-change="sortChange"
      :row-key="getRowKeys"
      :span-method="spanMethods"
    >
      <!--region 选择框-->
      <el-table-column v-if="isCheckBox"
        type="selection" align="center" style="width: 65px"
        :reserve-selection="true"
        :selectable="selectable"
      >
      </el-table-column>
      <!---seq 序列号--->
      <el-table-column v-if="isIndex" label="序号" type="index" align="center" width="65px" :fixed="indexFixed">
      </el-table-column>
      <!--endregion-->
      <!--region 数据列-->
      <template v-if="isMerge">
        <el-table-column
          v-for="(column, index) in normalColumns"
          :key="index"
          :prop="column.prop"
          :label="column.label"
          :align="column.align"
          :width="column.width"
          :sortable="column.sortable"
          :fixed="column.fixed"
          :formatter="column.formatter"
          :sort-orders="['descending', 'ascending', null]"
          show-overflow-tooltip
        >
          <template #default="scope" v-if="column.link">
            <div style="display: flex; align-items: center">
              <el-link type="primary" :underline="false" @click="()=>toVehicle(scope.row)">{{ scope.row[column.prop] }}</el-link>
            </div>
          </template>
          <template v-if="column.children?.length">
            <el-table-column
              v-for="(child, num) in column.children"
              :key="num"
              :prop="child.prop"
              :label="child.label"
              :align="child.align"
              :width="child.width"
              :sortable="child.sortable"
              :fixed="child.fixed"
              :formatter="child.formatter"
              :sort-orders="['descending', 'ascending', null]"
              show-overflow-tooltip
            >
            </el-table-column>
          </template>
        </el-table-column>
      </template>
      <template v-else>
      <el-table-column
        v-for="(column, index) in normalColumns"
        :key="index"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
        :sortable="column.sortable"
        :fixed="column.fixed"
        :formatter="column.formatter"
        :sort-orders="['descending', 'ascending', null]"
        show-overflow-tooltip
      >
        <template #header>
          <span v-if="column.isRequest" class="cellStar"></span>
          {{column.label}}
        </template>
        <template #default="scope">
          <template v-if="column.slot">
            <slot :name="column.slot" :scopeData="scope"></slot>
          </template>
          <template v-else-if="column.dictionary">
            <span>
              {{showLabel(column.dictionary, scope.row[column.prop])}}
            </span>
          </template>
          <template v-else>
            <span v-if="typeof scope.row[column.prop] === 'number' ">
              <span :class="scope.row.updateKeys ? (scope.row.updateKeys.indexOf(column.prop)>-1?'set_table_col':'') :''">
                {{ scope.row[column.prop]}}
              </span>
            </span>
            <span v-else>
              <span :class="scope.row.updateKeys ? (scope.row.updateKeys.indexOf(column.prop)>-1?'set_table_col':'') :''">
                {{ scope.row[column.prop] ? scope.row[column.prop] : '--' }}
              </span>
            </span>
          </template>
        </template>
      </el-table-column>
      </template>
    </el-table>
    <page-setting
      v-if="showPagination"
      class="page_setting"
      :currentPage="pageModel.currentPage"
      :pageSize="pageModel.pageSize"
      :totalCount="pageModel.totalCount"
      :layout="pageModel.layout"
      @pageChange="pageChange"
    />
  </div>
</template>
<!--endregion-->
<script lang="ts">

import { defineComponent, computed, ref, watch, onUpdated
  //  defineExpose
} from 'vue'
// import { format } from 'date-fns'
import ElConfigProvider from 'element-plus'
import { useRouter } from 'vue-router'
import PageSetting from './page-setting.vue'
// import moment from 'moment'

export default defineComponent({
  name: 'MenuList',
  props: {
    pageModel: {
      type: Object,
      default: () => {}
    },
    height: {
      type: String,
      default: () => {}
    },
    defaultSort: {
      type: Object,
      default: () => {}
    },
    // 数据列表
    list: {
      type: Array,
      default: () => []
    },
    /*
      需要展示的列 === prop：列数据对应的属性，label：列名，align：对齐方式，width：列宽
    */
    columns: {
      type: Array,
      default: () => []
    },
    border: {
      type: Boolean,
      default: true
    },
    loading: {
      type: Boolean,
      default: false
    },
    spanMethod: {
      type: Object,
      default: () => {}
    },
    /*
      操作按钮组 ===
      label: 文本，type :类型（primary / success / warning / danger / info / text）
      show：是否显示，icon：按钮图标
      plain：是否朴素按钮
      disabled：是否禁用,
      method：回调方法
    */
    operates: {
      type: Object,
      default: () => {}
    },
    // options: {
    //   type: Object,
    //   default: () => {
    //     {
    //       stripe: false,  //是否为斑马纹 table
    //       highlightCurrentRow: true // 是否要高亮当前行
    //     }
    //   }
    // } // table 表格的控制参数
    showScroll: {
      type: Boolean,
      default: true
    },
    showPagination: {
      type: Boolean,
      default: true
    },
    checkList: {
      type: Array,
      default: () => []
    },
    // 是否合并单元格
    isMerge: {
      type: Boolean,
      default: false
    },
    // 序号列是否固定
    indexFixed: {
      type: Boolean,
      default: false
    }
  },
  components: {
    [(ElConfigProvider as any).name]: ElConfigProvider,
    PageSetting,
  },
  setup(props, { emit }) {
    const router = useRouter()
    const mutipleTable = ref<any>()
    const normalColumns = ref<any>([])
    const sortable = 'custom'
    // 判断是否展示多选框
    const isCheckBox = computed(() => {
      return props.columns.some((item: any) => item.type === 'checkbox')
    })
    // 判断是否展示多选框
    const isIndex = computed(() => {
      return props.columns.some((item: any) => item.type === 'index')
    })
    const spanMethods = props.spanMethod ? props.spanMethod : null
    const handleSelectionChangeAll = (val: any) => {
      emit('handleSelectionChangeAll', val)
    }
    // 多行选中
    const handleSelectionChange = (val: any) => {
      emit('handleSelectionChange', val)
    }
    const selectable = (row: any) => {
      return row.isDisabled ? false : true
    }
    const handleCurrentChange = (val: any) => {
      emit('handleCurrentChange', val)
    }
    const sortChange = (column:any, prop:any, order:any) => {
      if (sortable === 'custom') {
        console.log(column, prop, order, '------sortChange--------')
        // let orderby = ''
        // if (column) {
        //   orderby = {
        //     fieldName: column.prop,
        //     sort: sortOrder[column.order]
        //   }
        // } else {
        //   orderby = ''
        // }
        // 去调用接口传递orderby参数即可
      }
    }
    const pageChange = (data: any) => {
      emit('search', data)
    }
    // 将定义的字符串函数 通过eval进行解析执行
    const convertHtml = (row:any, column:any) => {
      // console.log(column.html, 'html')
      let res
      if (column && column.html) {
        if (typeof column.html === 'object') {
          res = column.html(row, column)
        }
        if (typeof column.html === 'string') {
          // // 用eval调用没问题
          const evalFunction = JSON.parse(column.html)
          res = evalFunction(row, column)
        }
      }
      return res
    }
    const showLabel = (dictionary: any, data: string | number) => {
      const resData = dictionary.find((item:any) =>
        item.value === data || item.value === data.toString() || item.dictValueCode === data)
      const res = resData ? resData.label || resData.dictValueDesc : '--'
      return res
    }
    watch(
      () => props.columns,
      () => {
        normalColumns.value = props.columns.filter(
          (item: any) => !item.type || !['checkbox', 'index'].includes(item.type)
        )
      },
      {
        immediate: true,
        deep: true
      }
    )
    const getRowKeys = (row: any) => {
      return row.id
    }

    // 跳到单车报告
    const toVehicle = (row) => {
      router.push(row.link)
    }

    onUpdated(() => {
      const ids = props.checkList.map((item: any) => { return item.id })
      if (ids.length === 0) {
        mutipleTable.value?.clearSelection()
      } else {
        props.list.forEach((item: any) => {
          if (ids.includes(item.id)) {
            mutipleTable.value?.toggleRowSelection(item, true)
          } else {
            mutipleTable.value?.toggleRowSelection(item, false)
          }
        })
      }
    })
    return {
      isCheckBox,
      isIndex,
      normalColumns,
      spanMethods,
      handleSelectionChange,
      handleSelectionChangeAll,
      handleCurrentChange,
      sortChange,
      pageChange,
      convertHtml,
      selectable,
      mutipleTable,
      showLabel,
      getRowKeys,
      toVehicle
    }
  },
})
</script>

<style lang="less" scoped>
.item {
  display: inline;
  padding-right: 4px;
}
.table-img {
  width: 40px;
  height: 40px;
  border-radius: 3px;
}
.page_setting {
  display: flex;
  justify-content: flex-end;
}
.set_table_col{
  color:red;
}
.tool-tip {
  width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}
.cellStar:before{
    content: '*';
    padding-right: 5px;
    color: red;
  }

</style>
